<template>
  <div class="flex items-center justify-between border-b border-solid border-[#E8E8E8] py-[18px] px-[16px] main-header">
    <div class="flex items-center" v-if="!isRename">
      <span class="text-[20px] font-bold">
        {{ selectData?.name }}
      </span>
      <svg-icon @click.stop="onClickRename" name="icon_edit"
        class="w-[20px] h-[20px] ml-[8px] cursor-pointer"></svg-icon>
    </div>
    <div v-if="isRename" class="activeMenu p-[8px] flex items-center" v-on-click-outside="handleOutsideClick">
      <el-input style="width: 216px" class="input_rename" v-model="reName" clearable placeholder="请输入名称（1-40位）"
        maxlength="40" minlength="1" show-word-limit @clear="handleClear" @blur="handleBlur" />
      <img src="../../../../assets/images/check_icon.png" class="w-[32px] h-[32px] ml-[8px] cursor-pointer"
        @click.stop="handleRename" />
    </div>
    <div class="flex items-center">
      <!-- <div class="flex items-center">
        <span>创建人：</span>
        <img
          src="../../../../assets/images/persol.png"
          alt=""
          class="ml-[8px] mr-[4px] w-[20px] h-[20px]"
        />
        <span>李四</span>
      </div> -->
      <!-- <div class="w-[1px] h-[20px] bg-[#E8E8E8] mx-[16px]"></div> -->
      <!-- 分享协作/邀请协作 -->
      <img v-if="status != 0" src="../../../../assets/images/icon_share.png" alt=""
        class="w-[20px] h-[20px] mr-[16px] cursor-pointer" />
      <el-tooltip v-if="status == 0" class="box-item" effect="dark" content="邀请协作" placement="top-end">
        <span>
          <el-popover placement="bottom" title="" :width="480" trigger="click" content="" :show-arrow="false"
            @hide="onHide">
            <!-- 分享协作 -->
            <div>
              <div class="py-[13px] px-[16px] flex items-center justify-between border-b border-solid border-[#E8E8E8]">
                <span class="text-[18px] font-bold" v-show="!isInvite">分享协作</span>
                <div v-show="isInvite" class="flex items-center">
                  <el-icon class="mr-[8px] cursor-pointer" @click="isInvite = false">
                    <ArrowLeftBold />
                  </el-icon>
                  <span class="text-[18px] font-bold"> 邀请协作</span>
                </div>
                <el-icon @click="onClose" class="cursor-pointer">
                  <Close />
                </el-icon>
              </div>
              <div class="p-[24px]">
                <el-select :teleported="false" v-model="searchUser" filterable remote reserve-keyword
                  placeholder="请输入用户名、账号" :remote-method="remoteMethod" style="width: 432px" @focus="isInvite = true"
                  @change="onChange" value-key="id">
                  <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item">
                    <div class="flex items-center">
                      <img src="../../../../assets/images/persol.png" alt="" class="mr-[4px] w-[24px] h-[24px]" />
                      {{ item.name }} {{ item.loginName }}
                    </div>
                  </el-option>
                </el-select>
              </div>
              <div v-show="isInvite" class="pb-[24px]">
                <div class="min-h-[180px]">
                  <div v-if="selectUserList?.length" v-for="item in selectUserList" :key="item.id"
                    class="flex items-center justify-between py-[12px] px-[24px]">
                    <div class="flex items-center">
                      <img src="../../../../assets/images/persol.png" alt="" class="mr-[4px] w-[24px] h-[24px]" />
                      {{ item.name }}
                    </div>
                    <div class="flex items-center">
                      协作者
                      <el-icon @click="onClear(item)" class="cursor-pointer ml-[4px]">
                        <Close />
                      </el-icon>
                    </div>
                  </div>
                  <div v-else class="flex items-center justify-center mt-[40px]">
                    <img src="../../../../assets/images/no_share.png" alt="" class="w[120px] h-[120px]" />
                  </div>
                </div>
                <div class="flex items-center justify-end px-[24px]">
                  <Button type="primary" @click="onInvite">邀请协作</Button>
                </div>
              </div>
              <div class="py-[16px] border-t border-solid border-[#E8E8E8]" v-show="!isInvite && shareUser?.length">
                <div v-for="item in shareUser" :key="item.id"
                  class="flex items-center justify-between py-[12px] px-[24px]">
                  <div class="flex items-center">
                    <img src="../../../../assets/images/persol.png" alt="" class="mr-[4px] w-[24px] h-[24px]" />
                    {{ item.beUserName }}
                  </div>
                  <div class="flex items-center">
                    协作者
                    <el-icon @click="onDetele(item)" class="cursor-pointer ml-[4px]">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
            <!-- 邀请协作 -->
            <div></div>
            <template #reference>
              <div class="iconLine">
                <img src="../../../../assets/images/share_icon.png" alt="" class="w-[20px] h-[20px]" />
              </div>
            </template>
          </el-popover>
        </span>
      </el-tooltip>
      <el-tooltip class="box-item" effect="dark" content="原始数据上传记录" placement="top-end">
        <div class="iconLine" @click="open">
          <img src="../../../../assets/images/data_icon.png" alt="" class="w-[20px] h-[20pxd]" />
        </div>
        <!-- <el-icon class="ml-[16px]" @click="open"><CirclePlusFilled /></el-icon> -->
      </el-tooltip>
      <div class="w-[1px] h-[20px] bg-[#E8E8E8] mx-[16px]"></div>
      <input ref="fileInputRef" type="file" multiple accept="*/*"
        style="display: none" :key="fileInputKey" @change="handleFileUpload" />
      <Button :type="tableData?.length ? 'cancel' : 'disabled'" class="ml-[16px]"
        @click="triggerFileUpload">上传文件</Button>
      <Button :type="tableData?.length ? 'cancel' : 'disabled'" class="ml-[16px]" @click="handleDetele()">删除所选</Button>
      <Button :type="tableData?.length ? 'cancel' : 'disabled'" class="ml-[16px]" @click="onExpose()">导出所选</Button>
      <Button :type="tableData?.length ? 'primary' : 'disabled'" class="ml-[16px]" @click="handleExpose">导出全部</Button>
    </div>
  </div>
  <!-- 解析完成 -->
  <template v-if="status == 0">
    <div class="flex items-center px-[16px] py-[20px] main-header">
      <span>数据类型：</span>
      <ul class="flex items-center">
        <li :class="`dataItem ${activeId == item.id ? 'active' : ''}`" v-for="item in tabList" :key="item.id"
          @click="onTabClick(item)">
          {{ item.name }}
        </li>
      </ul>
      <div class="ml-[60px]">关键字：</div>
      <el-input style="width: 240px" v-model="search" clearable placeholder="请输入" @clear="handleSearchClear"
        @keyup.enter="onSearchInput">
        <!-- @clear="onSearchInput" -->
        <!-- @keyup.enter="onSearchInput" -->
      </el-input>

      <Button type="primary" class="ml-[60px]" @click="onSearchInput"
        v-loading.fullscreen.lock="fullscreenLoading">查询</Button>
      <Button type="cancel" class="ml-[16px]" @click="ocClear" v-loading.fullscreen.lock="fullscreenLoading">重置</Button>
    </div>
    <div class="px-[16px] tableLine main-header">
      <div class="overflow-y-hidden bg-[#fff]">
        <el-table border align="left" :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="_uid"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="60" />
          <el-table-column type="index" label="序号" width="70" />
          <el-table-column prop="xm" label="姓名" width="260" />
          <el-table-column prop="sfzh" label="身份证号" width="430" />
          <el-table-column prop="type" label="数据类型" width="300">
            <template #default="{ row }">
              <span>{{ getType(row.type) }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="number" label="数量" width="210" /> -->
          <el-table-column prop="caseFiles" label="原始数据来源" width="216">
            <template #default="{ row }">
              <el-popover placement="bottom-start" title="" :width="400" trigger="hover" content="" :show-arrow="false"
                :popper-style="{ minWidth: '300px' }">
                <template #reference>
                  <span class="text-[#1a66ff] cursor-pointer">
                    {{ row.caseFiles?.length }}
                  </span>
                </template>
                <div class="overflow-auto max-h-[300px]">
                  <div v-for="item in row.caseFiles" :key="item.id" class="px-[8px] py-[8px] overflow-y-hidden">
                    {{ item.originalName }}
                  </div>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="176">
            <template #default="{ row }">
              <div class="table-buttons">
                <!-- <span @click="viewInfo(row, '查看')">查看</span> -->
                <span @click="onExpose(row)">导出</span>
                <span @click="handleDetele(row)">删除</span>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="无查询结果" />
          </template>
        </el-table>
      </div>
    </div>
    <page class="place-self-end" :options :change="change" :handleSizeChange="handleSizeChange"></page>
  </template>
  <!-- 解析中 -->
  <div class="w-[980px] mt-[48px] tableLine mx-auto main-header" v-if="status == 2">
    <div class="card">
      <div class="flex items-center justify-between py-[13px] px-[16px] border-b border-solid border-[#E8E8E8]">
        <span class="text-[18px] font-bold">文件解析</span>
        <!-- <el-icon><Close /></el-icon> -->
      </div>
      <div class="py-[24px] px-[40px]">
        <div class="mb-[16px] flex items-center">
          <img src="../../../../assets/images/icon_detele.png" alt="" class="w-[20px] h-[20px] mr-[8px]"
            v-if="nadState == 2" />
          <div class="circle-loader" v-else></div>
          <span class="font-bold">
            {{
              nadState == 1
                ? "文件解析完成"
                : nadState == 2
                  ? "文件解析中断"
                  : "文件解析中..."
            }}
          </span>
          {{ percentAge }}%
        </div>
        <div class="flex items-center justify-between mb-[12px]" v-for="item in list" :key="item.id">
          <span class="truncate">{{ item.jxrz }}</span>
          <span class="min-w-[160px] ml-[20px]">{{
            dayjs(item?.createdTime).format("YYYY-MM-DD HH:mm:ss")
            }}</span>
        </div>
      </div>
    </div>
  </div>
  <!-- 解密中 -->
  <div v-if="status == 1" class="mt-[48px] tableLine mx-auto main-header">
    <div class="card">
      <div class="flex items-center justify-between py-[13px] px-[16px] border-b border-solid border-[#E8E8E8]">
        <span class="text-[18px] font-bold">文件解密</span>
        <!-- <el-icon><Close /></el-icon> -->
      </div>
      <div class="py-[24px] px-[40px]">
        <div class="flex items-center justify-between mb-[20px]">
          <div class="flex items-center">
            <img src="../../../../assets/images/stop.png" alt="" v-if="stopNext" class="w-[16px] h-[16px] mr-[4px]" />
            <div class="circle-loader" v-else></div>
            <span>{{ title }} </span>
            <!-- {{ percentAge }}% -->
            <div v-if="failState" class="text-[#F5771D] ml-[20px] flex items-center">
              <el-icon class="mr-[4px]">
                <InfoFilled />
              </el-icon>请处理完解密失败的文件，方可进行解析
            </div>
          </div>
          <Button type="primary" class="ml-[16px]" @click="onAnalyDetele()">删除所选</Button>
        </div>
        <el-table border align="left" :data="analysisList" row-key="_uid" @selection-change="handleSelection" >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="originalName" label="文件名称" width="360" />
          <el-table-column prop="originalPath" label="文件位置" width="272" />
          <el-table-column prop="fileStatus" label="解析状态" width="352">
            <template #default="{ row }">
              <div class="flex items-center justify-between" v-if="!row.flag">
                <div class="flex items-center">
                  <div :class="`${row.fileStatus == '2' ? 'fail' : 'sussess'}`"></div>
                  <span>{{ row.fileStatus == "2" ? "解密失败" : "成功" }}</span>
                </div>
                <span v-if="row.fileStatus == '2'" @click="onInput(row)" :class="[
                  'text-[#1a66ff] cursor-pointer',
                  // 如果其他文件正在输入密码，禁用当前文件
                  currentPasswordFileId && currentPasswordFileId !== row.id ? 'opacity-50 cursor-not-allowed' : ''
                ]" :title="currentPasswordFileId && currentPasswordFileId !== row.id ? '请先完成当前密码输入' : '点击输入密码'">
                  输入密码
                </span>
              </div>

              <div v-if="row.flag" class="flex items-center">
                <el-input style="width: 240px" class="nameInput" ref="nameInput" v-model="password" placeholder="请输入密码"
                  @keyup.enter="submitPassword(row)" ></el-input>
                <el-icon class="mx-[18px] w-[20px] h-[16px] cursor-pointer text-green-500 hover:text-green-600"
                  @click="submitPassword(row)" title="确认密码" >
                  <Check />
                </el-icon>
                <el-icon class="w-[16px] h-[16px] cursor-pointer text-red-500 hover:text-red-600"
                  @click="cancelPasswordInput(row)" title="取消输入">
                  <Close />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="{ row }">
              <div class="table-buttons">
                <span @click="onAnalyDetele(row)">删除</span>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="无查询结果" />
          </template>
        </el-table>
      </div>
    </div>
  </div>
  <Drawer ref="drawerRef" :caseId="selectData.id" />
</template>
<script setup>
import dayjs from "dayjs";
import { vOnClickOutside } from '@vueuse/components'
import Drawer from "./drawer.vue";
import { Delmessage } from "@/utils/message.js";
import { ElLoading, ElMessage } from "element-plus";
import { antiShake } from "@/utils/antiShakingAndThrottling";
import api from "@/api";
const multipleSelection = ref([]);
const search = ref("");
const searchUser = ref(null);
const drawerRef = ref();
const fileInputRef = ref();
// const detailRef = ref();
// const detailId = ref("");
const activeId = ref(0);
const shareUser = ref([]);
const isInvite = ref(false); //展示邀请协作
const selectUserList = ref([]);
const list = ref([]);
const percentAge = ref(0);
const nadState = ref(null); // 0:解析中 1:解析完成 2:解析失败
const status = ref(null); // 0:解析完成 1:解密中 2:解析中
const password = ref("");
const failState = ref(false);
const stopNext = ref(false);
const title = ref("文件解密中");
const analysisList = ref([]);
const checkList = ref([]);
const isRename = ref(false); // 是否重命名
const reName = ref(""); // 重命名内容
const fullscreenLoading = ref(false);
const fileInputKey = ref(0); // 用于强制刷新 file input 的 key
let timerId;
const options = reactive({
  total: 0,
  pageSize: 10,
  pageNum: 1,
});
const userOptions = ref([]);
const tabList = ref([
  {
    name: "全部",
    id: 0,
  },
  {
    name: "人员信息",
    id: 1,
  },
  {
    name: "账单",
    id: 2,
  },
  {
    name: "话单",
    id: 3,
  },
]);
const tableData = ref([]);
const emit = defineEmits(["handleRename"]);
const { selectData } = defineProps({
  selectData: {
    type: Object,
    default: {},
  },
});
// 导出全部
const handleExpose = async () => {
  fullscreenLoading.value = true;
  let [err, res] = await api.getAllexport(selectData.id);
  fullscreenLoading.value = false;
  if (err) return;
  let a = document.createElement("a");
  a.style.display = "none";
  a.href = res.data;
  a.download = "";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};
//  目录重命名
const handleRename = async () => {
  // let [err, res] = await api.a();
  // if (err) return;
  // queryList();
  emit("handleRename", reName.value);
  isRename.value = false;
};
// 导出和搜索加载过慢，引入loading状态
const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  setTimeout(() => {
    loading.close();
  }, 2000);
};
const getType = (type) => {
  const typeName = tabList.value.find((item) => item.id == type);
  return typeName ? typeName.name : "";
};
// 删除账单
const handleDetele = (row) => {
  if (!multipleSelection.value?.length && !row)
    return ElMessage.success({
      message: "请选择数据删除",
      showClose: true,
    });
 
  // 根据选择数量显示不同的提示内容
  let content = "";
  let data = null
  if(row){
    content = "是否删除当前记录？";
    data = [row]
  }else{
    content = "是否删除所选数据？";
    data = multipleSelection.value
  }
  // const isMultiple = multipleSelection.value?.length > 0;

  // if (isMultiple) {
  //   // 多选数据
  //   content = "是否删除所选数据？";
  // } else {
  //   // 单条数据
  //   content = "是否删除当前记录？";
  // }

  const close = Delmessage({
    title: "删除确认",
    content: content,
    submitText: "删除",
    cancel() {
      close();
    },
    submit: antiShake(async () => {
      
      let [err] = await api.delAnalysis({
        caseId: selectData.id,
        deleteData: data,
      });
      if (err) return;
      getTablelist();
      ElMessage.success({
        message: "删除成功",
        showClose: true,
      });
      close();
    }),
  });
};
// 导出文件
const onExpose = async (row) => {
  if (!multipleSelection.value?.length && !row)
    return ElMessage.success({
      message: "请选择数据进行导出",
      showClose: true,
    });
  fullscreenLoading.value = true;
  let  data = null
  if(row){
    data = [row]
  }else{
    data = multipleSelection.value
  }
  // const data = multipleSelection.value.length ? multipleSelection.value : [row];
  let [err, res] = await api.getExport({
    caseId: selectData.id,
    exportData: data,
  });
  fullscreenLoading.value = false;
  if (err) return;
  let a = document.createElement("a");
  a.style.display = "none";
  a.href = res.data;
  a.download = "";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};
// 选择用户
const onChange = () => {
  const flag = selectUserList.value.some(
    (item) => item.id == searchUser.value.id
  );
  if (flag) return;
  selectUserList.value.push(searchUser.value);
  searchUser.value = null;
};
// 清除选择的用户
const onClear = (row) => {
  selectUserList.value = selectUserList.value.filter(
    (item) => item.id != row.id
  );
  // activeId.value = 0;

};
// 删除已经分享过的用户
const onDetele = async (item) => {
  const close = Delmessage({
    title: "删除确认",
    content: "是否删除此共享成员？",
    submitText: "删除",
    cancel() {
      close();
    },
    submit: antiShake(async () => {
      let [err, res] = await api.delUser(item.id);
      if (err) return;
      getList();
      ElMessage.success({
        message: "删除成功",
        showClose: true,
      });
      close();
    }),
  });
};
// 触发文件选择
const triggerFileUpload = () => {
  // if (status.value != 0) return;
  fileInputRef.value.click();
};

// 文件格式验证
const beforeUpload = (file) => {
  const extension = file.name.split(".").pop();
  const allowedFormats = [
    "zip", "7z", "tar", "gz", "gzip", "bz2", "bzip2", "tgz", "xlsx", "txt"
  ];

  if (extension && !allowedFormats.includes(extension)) {
    ElMessage.error(
      "上传文件只能是 zip、7z、tar、gz、gzip、bz2、bzip2、tgz、xlsx、txt 格式!"
    );
    return false;
  }
  return true;
};

// 处理文件上传
const handleFileUpload = async (event) => {
  const files = Array.from(event.target.files);
  if (files.length === 0) return;

  // 验证文件格式
  for (const file of files) {
    if (!beforeUpload(file)) {
      // 由于使用了 key 强制刷新，不需要手动清空 input 值
      return;
    }
  }

  // 检查是否为二次上传
  // if (tableData.value && tableData.value.length > 0) {
  //   const closeDialog = Delmessage({
  //     title: "二次上传确认",
  //     content: "当前案件已存在数据，继续上传将覆盖现有数据，是否继续？",
  //     submitText: "继续上传",
  //     cancel() {
  //       closeDialog();
  //       // 清空文件输入框
  //       event.target.value = '';
  //     },
  //     submit: antiShake(async () => {
  //       await uploadFiles(files);
  //       closeDialog();
  //       // 清空文件输入框
  //       event.target.value = '';
  //     }),
  //   });
  // } else {
  //   // 直接上传
  //   await uploadFiles(files);
  //   // 清空文件输入框
  //   event.target.value = '';
  // }
  await uploadFiles(files);

  // 更新 fileInputKey，强制刷新 DOM
  fileInputKey.value++;
  console.log('更新 fileInputKey:', fileInputKey.value);
};

// 执行文件上传
const uploadFiles = async (files) => {
  try {
    fullscreenLoading.value = true;

    // 使用现有的上传逻辑
    const formData = new FormData();
    files.forEach((file) => {
      formData.append("files", file);
    });

    // 判断是继续上传还是新建上传
    const apiType = selectData.id
      ? api.upKeepload(selectData.id, formData)
      : api.upload(formData);

    const [err, res] = await apiType;

    if (err) {
      ElMessage.error('文件上传失败');
      return;
    }

    ElMessage.success('文件上传成功');

    // 上传成功后，重新获取状态和数据
    await handleStatus();

    // 再次更新 fileInputKey，确保下次选择文件时 DOM 完全刷新
    fileInputKey.value++;
    console.log('上传完成后更新 fileInputKey:', fileInputKey.value);

  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  } finally {
    fullscreenLoading.value = false;
  }
};
// 模糊搜索
const remoteMethod = (query) => {
  if (query) {
    setTimeout(async () => {
      let [err, res] = await api.getUserList({ keyword: query });
      if (err) return;
      userOptions.value = res.data;
    }, 200);
  } else {
    userOptions.value = [];
  }
};
// popver关闭时默认初始值-分享协作
const onHide = () => {
  isInvite.value = false;
  selectUserList.value = [];
};
const onClose = () => {
  document.body.click();
};
// 分享协作输入框获得焦点展示邀请协作
// const onFocus = () => {
// isInvite.value = !isInvite.value;
// document.body.click();
// console.log(isInvite.value, "isInvite.value888");
// };
// 打开原始数据抽屉
const open = () => {
  drawerRef.value.onOpen();
};
// 添加一个标志位，防止重复请求


const onTabClick = async (item) => {
  // 防止重复请求

  // 如果正在重命名，强制退出重命名状态
  if (isRename.value) {
    console.log('点击tab标签，强制退出重命名状态');
    isRename.value = false;
    reName.value = '';

    // 强制让输入框失焦
    const inputElement = document.querySelector('.input_rename input');
    if (inputElement) {
      inputElement.blur();
    }
  }

  try {

    // 重置分页状态
    options.pageNum = 1;
    options.pageSize = 10;

    activeId.value = item.id;
    search.value = '';

    // 重新获取数据
    await getTablelist();

  } finally {

  }
};
// const onSearchUser = () => {
//   console.log(searchUser.value);
// };
// 重置
const ocClear = () => {
  // 如果正在重命名，强制退出重命名状态
  if (isRename.value) {
    console.log('重置操作，强制退出重命名状态');
    isRename.value = false;
    reName.value = '';

    // 强制让输入框失焦
    const inputElement = document.querySelector('.input_rename input');
    if (inputElement) {
      inputElement.blur();
    }
  }

  search.value = "";
  activeId.value = 0;
  options.pageSize = 10;
  options.pageNum = 1;
  getTablelist();
};
// 查询
const onSearchInput = async () => {
  options.pageSize = 10;
  options.pageNum = 1;
  getTablelist();
};
// 每页显示个数切换
const handleSizeChange = (value) => {
  options.pageSize = value;
  getTablelist();
};
// 页码切换
const change = (val) => {
  options.pageNum = val;
  getTablelist();
};
// 查看文件
// const viewInfo = (row) => {
//   console.log(row);
//   detailId.value = row.id;
//   detailRef.value.onOpen();
// };
// 表格勾选的数据
const handleSelectionChange = (value) => {
  console.log('选择变化:', value);
  console.log('当前表格数据:', tableData.value);
  multipleSelection.value = value;
  console.log('已选择的数据:', multipleSelection.value);
};
// 获取数据列表
const queryList = async () => {
  await getResolver();
  if (nadState.value == 0) {
    getSetInterval();
  }
};
// 解析中
const getResolver = async () => {
  if (!selectData.id) return;
  let [err, res] = await api.getNadlog(selectData.id);
  if (err) return;
  list.value = res.data.logs;
  percentAge.value = res.data.percentage;
  nadState.value = res.data.jxzt; // 0:解析中 1:解析完成 2:解析失败
  // 解析完成调取结果接口
  if (res.data.jxzt == 1) {
    clearInterval(timerId); //清楚定时器
    ElMessage.success({
      message: "解析成功",
      showClose: true,
    });
    status.value = 0;
    getTablelist();
    getList();
  }
};
// 解析完成后数据获取
let rowIdCounter = 0;

const getTablelist = async () => {
  try {
    fullscreenLoading.value = true;

    let [error, result] = await api.getAnalysisList({
      caseId: selectData.id,
      keyword: search.value,
      type: activeId.value,
      pageNum: options.pageNum,
      pageSize: options.pageSize,
    });

    if (error) return;

    fullscreenLoading.value = false;

    // 只保留自身数据和 _uid
    tableData.value = (result.data.records || []).map((item, index) => {
      rowIdCounter++;
      return {
        ...item,
        _uid: `tab_${activeId.value}_page_${options.pageNum}_seq_${rowIdCounter}`
      };
    });

    options.total = result.data.total;

  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('请求被取消');
      return;
    }
    console.error('获取数据失败:', error);
  }
};
// 定时器进度条
const getSetInterval = () => {
  timerId = setInterval(() => {
    if (!selectData.id || nadState.value != 0) clearInterval(timerId);
    getResolver();
  }, 5000);
};
// 已分享人员列表
const getList = async () => {
  let [err, res] = await api.getUser(selectData.id);
  if (err) return;
  shareUser.value = res.data;
};
// 分享邀请用户
const onInvite = async () => {
  const ids = selectUserList.value.map((item) => item.id);
  let [err, res] = await api.getShare({
    caseId: selectData.id,
    beUserIds: ids,
  });
  if (err) return;
  ElMessage.success({
    message: "邀请成功",
    showClose: true,
  });
  selectUserList.value = [];
  onClose();
  getList();
};
// 判断当前文件处于什么状态
const handleStatus = async () => {
  let [err, res] = await api.getStatus(selectData.id);
  if (err) return;
  status.value = res.data;
  tableData.value = [];
  if (status.value == 0) {
    getTablelist(); // 解析完成
    getList();
  } else if (status.value == 1) {
    getDecode(); // 解密中
  } else if (status.value == 2) {
    queryList(); // 解析中
    // getSetInterval(); // 定时器
  }
};
// 解密

// 解密删除文件
const onAnalyDetele = async (row) => {
  if (!checkList.value?.length && !row)
    return ElMessage.success({
      message: "请选择数据删除",
      showClose: true,
    });
  let content =''
  if(row){
    content = "是否删除本条记录？";
  }else{
    content = "是否删除所选数据？";
  }
  const close = Delmessage({
    title: "删除确认",
    content: content,
    submitText: "删除",
    cancel() {
      close();
    },
    submit: antiShake(async () => {
      try {
        let ids = [];
        if (row) {
          ids = [row.id];
        } else {
          ids = checkList.value?.map((item) => {
            return item.id;
          });
        }

        let [err, res] = await api.getDetele({
          ids,
        });

        if (err) return;

        ElMessage.success({
          message: "删除成功",
          showClose: true,
        });

        // 重新获取解密文件列表
        getDecode();
        close();
      } catch (error) {
        console.error('删除文件失败:', error);
        ElMessage.error('删除失败');
      }
    }),
  });
};
// 解密文件数据获取
const getDecode = async (loading = null) => {
  let [err, res] = await api.getFileList({
    caseId: selectData.id,
    isPage: 1,
  });
  clearInterval(timerId);
  title.value = "文件解密已终止";
  if (err) {
    return;
  }
  stopNext.value = true;

  // 只保留自身数据和 _uid
  analysisList.value = (res.data || []).map((item, index) => ({
    ...item,
    _uid: `decrypt_${index}`
  }));

  console.log('解密表格数据:', analysisList.value);
  failState.value = analysisList.value.some((item) => item.fileStatus == "2");
  percentAge.value = failState.value ? 90 : 100;
  // 解密都成功时
  if (!failState.value) {
    ElMessage.success({
      message: "解密成功",
      showClose: true,
    });
    status.value = 2; // 解析中
    percentAge.value = 0;
    queryList();
  }
  
  // 关闭loading状态
  if (loading) {
    loading.close();
  }
};
// 添加一个变量来跟踪当前正在输入密码的文件ID
const currentPasswordFileId = ref(null);

// 修改输入密码的方法
const onInput = async (row) => {
  // 如果已经有其他文件在输入密码，禁止操作
  if (currentPasswordFileId.value && currentPasswordFileId.value !== row.id) {
    ElMessage.warning('请先完成当前密码输入');
    return;
  }

  // 设置当前文件为输入密码状态
  currentPasswordFileId.value = row.id;
  row.flag = true;

  // 清空密码输入框
  password.value = '';

  console.log('开始输入密码，文件ID:', row.id);
};

// 修改提交密码的方法
const submitPassword = async (row) => {
  // 创建全屏loading
  const loading = ElLoading.service({
    lock: true,
    text: '文件解密中...',
    background: 'rgba(0, 0, 0, 1)',
  });

  try {
    let [err, res] = await api.getFile({
      id: row.id,
      password: password.value,
    });

    if (err) {
      loading.close();
      return;
    }

    // 密码输入成功，重置状态
    currentPasswordFileId.value = null;
    row.flag = false;
    password.value = '';

    title.value = "文件解密中";
    // 传递loading实例给getDecode函数
    getDecode(loading);

  } catch (error) {
    console.error('密码输入失败:', error);
    ElMessage.error('密码输入失败');
    loading.close();
  }
};

// 添加取消密码输入的方法
const cancelPasswordInput = (row) => {
  // 重置状态
  currentPasswordFileId.value = null;
  row.flag = false;
  password.value = '';
  console.log('取消密码输入，文件ID:', row.id);
};
// 解密选择的文件
const handleSelection = (value) => {
  console.log('解密表格选择变化:', value);
  console.log('解密表格数据:', analysisList.value);
  checkList.value = value;
  console.log('已选择的解密文件:', checkList.value);
};
// 定时器进度条
// const getSetInterval = () => {
//   timerId = setInterval(() => {
//     if (percentAge.value > 90) {
//       clearInterval(timerId);
//     } else {
//       percentAge.value = (percentAge.value % 100) + 9;
//     }
//   }, 200);
// };
//   const getTypeList = () => {

// }
watch(
  () => selectData,
  (val, old) => {
    if (val.id) {
      clearInterval(timerId); // 清除定时器
      // queryList();
      // getList();
      handleStatus();
      reName.value = val.name;
    }
  }
  // { deep: true }
  // { immediate: true }
);
const handleclose = () => {
  isRename.value = false;
};
defineExpose({
  handleclose,
  resetActiveId: () => {
    activeId.value = 0;
    search.value = '';
    options.pageNum = 1;
    options.pageSize = 10;
    tableData.value = []
    //清除俩个表格的选中
    checkList.value = []
    multipleSelection.value = []
    // 重新获取数据，确保显示"全部"类型的数据
    //getTablelist();
  }
});
onMounted(() => {
  // getList();

  // 添加全局点击监听器，确保点击其他地方时退出重命名状态
  //document.addEventListener('click', handleGlobalClick);
});

onUnmounted(() => {
  // 移除全局点击监听器
  //document.removeEventListener('click', handleGlobalClick);
});
const handleOutsideClick = () => {
  console.log('点击外部，退出编辑状态')
  isRename.value = false
  reName.value = ''
}
// 全局点击处理
// const handleGlobalClick = (event) => {
//   // 如果不在重命名状态，直接返回
//   if (!isRename.value) return;

//   // 检查点击的元素是否在重命名区域内
//   const renameContainer = document.querySelector('.activeMenu');
//   if (renameContainer && !renameContainer.contains(event.target)) {
//     console.log('点击了重命名区域外，退出编辑状态');
//     isRename.value = false;
//     reName.value = '';

//     // 强制让输入框失焦
//     const inputElement = document.querySelector('.input_rename input');
//     if (inputElement) {
//       inputElement.blur();
//     }
//   }
// };

// 移除鼠标事件监听器，使用更可靠的全局点击监听器

// 移除搜索区域的鼠标事件监听器
// 处理输入框失焦事件
const handleBlur = () => {
  // 延迟执行，避免与点击事件冲突
  setTimeout(() => {
    // 检查是否真的失去了焦点
    const activeElement = document.activeElement;
    const renameContainer = document.querySelector('.activeMenu');

    // 如果当前激活的元素在重命名区域内，不要退出编辑状态
    if (renameContainer && renameContainer.contains(activeElement)) {
      console.log('焦点仍在重命名区域内，保持编辑状态');
      return;
    }

    // 如果点击了清除按钮，不要退出编辑状态
    if (activeElement && activeElement.classList.contains('el-input__clear')) {
      console.log('点击了清除按钮，保持编辑状态');
      return;
    }

    // 如果焦点真的离开了重命名区域，退出编辑状态
    console.log('输入框失焦，退出重命名状态');
    isRename.value = false;
    reName.value = '';
  }, 100);
};
// 处理搜索框清空事件
const handleSearchClear = () => {
  console.log('搜索框清空，显示所有内容');
  // 清空搜索关键词
  search.value = '';
  // 重新获取所有数据
  onSearchInput();
};
// 处理清除按钮点击事件
const handleClear = () => {
  // 只清空输入值，不退出编辑状态
  reName.value = '';
  console.log('清除按钮点击，清空输入值但保持编辑状态');

  // 阻止事件冒泡，避免触发失焦事件
  event?.stopPropagation();
};

// 点击重命名按钮，进入编辑状态
const onClickRename = () => {
  isRename.value = true;
  // 确保输入框显示当前名称
  reName.value = selectData?.name || '';
};
</script>
<style lang="scss" scoped>
.table-main {
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
  background: linear-gradient(180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.4) 100%);

  .input_rename {
    border: 1px solid rgba(11, 73, 217, 1);
    border-radius: 4px;
    box-shadow: 0px 0px 0px 2px rgba(26, 102, 255, 0.3);
    background: rgba(255, 255, 255, 1);
  }

  .iconLine {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      background: rgba(221, 221, 221, 0.4);
    }
  }

  

  .dateLine {
    display: flex;
    margin-left: 20px;
    // width: 160px;
    flex-wrap: nowrap;
    flex-shrink: 0;
  }

  .tableLine {
    flex: 1;
    overflow: auto;
  }

  .dataItem {
    cursor: pointer;
    margin-right: 12px;
    padding: 4px 16px;
    border: 1px solid rgba(221, 221, 221, 1);
    border-radius: 4px;
    background: rgba(255, 255, 255, 1);

    &.active {
      border: none;
      color: #fff;
      background: rgba(26, 102, 255, 1);
    }
  }

  .dataItem:last-of-type {
    margin-right: 0;
  }
}

.table-buttons {
  span {
    color: #1a66ff;
    cursor: pointer;
    margin-right: 16px;
  }

  span:last-of-type {
    margin-right: 0;
  }
}

.card {
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 1);
}

.circle-loader {
  margin-right: 4px;
  background-image: url(images/icon-loading.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.sussess {
  margin-right: 8px;
  width: 10px;
  height: 10px;
  border-radius: 20px;
  background: rgba(19, 194, 49, 1);
}

.fail {
  margin-right: 8px;
  width: 10px;
  height: 10px;
  border-radius: 20px;
  background: rgba(224, 27, 43, 1);
}
</style>